package src;

import javax.swing.*;
import java.awt.*;

public class WithdrawDialog extends JDialog {
    private String cardNumber;
    private JTextField amountField;
    private boolean confirmed = false;

    public WithdrawDialog(Frame owner, String cardNumber) {
        super(owner, "取款", true);
        this.cardNumber = cardNumber;
        setSize(300, 200);
        setLocationRelativeTo(owner);

        JPanel panel = new JPanel(new GridLayout(4, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 显示卡号
        panel.add(new JLabel("卡号:"));
        panel.add(new JLabel(cardNumber));

        // 输入金额
        panel.add(new JLabel("取款金额:"));
        amountField = new JTextField();
        panel.add(amountField);

        // 添加按钮
        JButton confirmButton = new JButton("确认取款");
        JButton cancelButton = new JButton("取消");

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(confirmButton);
        buttonPanel.add(cancelButton);
        panel.add(buttonPanel);

        // 添加事件监听器
        confirmButton.addActionListener(e -> {
            if (validateInput()) {
                int result = JOptionPane.showConfirmDialog(
                    this,
                    "确认取出 " + amountField.getText() + " 元？",
                    "确认取款",
                    JOptionPane.YES_NO_OPTION
                );
                
                if (result == JOptionPane.YES_OPTION) {
                    confirmed = true;
                    dispose();
                }
            }
        });

        cancelButton.addActionListener(e -> dispose());

        add(panel);
    }

    private boolean validateInput() {
        try {
            double amount = Double.parseDouble(amountField.getText().trim());
            if (amount <= 0) {
                JOptionPane.showMessageDialog(this, "取款金额必须大于0！", "错误", JOptionPane.ERROR_MESSAGE);
                return false;
            }
            // TODO: 检查余额是否足够
            if (amount > 1000) { // 示例：假设余额为1000
                JOptionPane.showMessageDialog(this, "余额不足！", "错误", JOptionPane.ERROR_MESSAGE);
                return false;
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "请输入有效的金额！", "错误", JOptionPane.ERROR_MESSAGE);
            return false;
        }
        return true;
    }

    public boolean isConfirmed() {
        return confirmed;
    }

    public double getAmount() {
        return Double.parseDouble(amountField.getText().trim());
    }
} 